import BaseController from './BaseController.js';
import db from '../models/index.js';
import { StatusCodes } from 'http-status-codes';
import { Op } from 'sequelize';
import { AppError } from '../middlewares/error.js';

const { Course, User, Enrollment } = db;

class CourseController extends BaseController {
  constructor() {
    super();
  }

  /**
   * 获取所有课程
   */
  async getAllCourses(req, res, next) {
    try {
      const { 
        page = 1, 
        limit = 10, 
        teacherId, 
        status, 
        keyword,
        sortBy = 'createdAt',
        sortOrder = 'DESC'
      } = req.query;

      const where = {};

      // 过滤条件
      if (teacherId) where.teacherId = teacherId;
      if (status) where.status = status;

      // 关键字搜索（课程名称或描述）
      if (keyword) {
        where[Op.or] = [
          { name: { [Op.like]: `%${keyword}%` } },
          { description: { [Op.like]: `%${keyword}%` } }
        ];
      }

      // 排序
      const order = [];
      if (sortBy) {
        order.push([sortBy, sortOrder || 'DESC']);
      }

      // 简化查询，先只查课程基本信息
      const result = await Course.findAndCountAll({
        where,
        order,
        offset: (page - 1) * limit,
        limit: parseInt(limit, 10),
        distinct: true
      });

      return this.success(res, {
        total: result.count,
        page: parseInt(page, 10),
        limit: parseInt(limit, 10),
        data: result.rows,
      }, '获取成功');
    } catch (error) {
      console.error('获取课程列表失败:', error);
      return this.error(res, '获取课程列表失败', StatusCodes.INTERNAL_SERVER_ERROR, error);
    }
  }

  /**
   * 创建课程（教师）
   */
  async createCourse(req, res, next) {
    try {
      // 只有教师可以创建课程
      if (req.user.role !== User.ROLES.TEACHER && req.user.role !== User.ROLES.ADMIN) {
        return next(
          new AppError('只有教师可以创建课程', StatusCodes.FORBIDDEN)
        );
      }

      // 设置教师ID为当前用户ID
      const courseData = {
        ...req.body,
        teacherId: req.user.id
      };

      const course = await Course.create(courseData);
      this.success(res, course, '课程创建成功', StatusCodes.CREATED);
    } catch (error) {
      this.error(res, '创建课程失败', StatusCodes.INTERNAL_SERVER_ERROR, error);
    }
  }

  /**
   * 获取课程详情
   */
  async getCourse(req, res, next) {
    try {
      const { id } = req.params;

      const course = await Course.findByPk(id, {
        include: [
          {
            model: User,
            as: 'teacher',
            attributes: ['id', 'name', 'email']
          },
          {
            model: Enrollment,
            as: 'enrollments',
            include: [
              {
                model: User,
                as: 'student',
                attributes: ['id', 'name', 'email']
              }
            ]
          }
        ]
      });

      if (!course) {
        return next(
          new AppError('未找到该课程', StatusCodes.NOT_FOUND)
        );
      }

      // 计算剩余名额
      const courseJson = course.toJSON();
      courseJson.availableSeats = course.capacity - course.currentEnrollment;

      this.success(res, courseJson, '获取成功');
    } catch (error) {
      this.error(res, '获取课程详情失败', StatusCodes.INTERNAL_SERVER_ERROR, error);
    }
  }

  /**
   * 更新课程信息（课程创建者或管理员）
   */
  async updateCourse(req, res, next) {
    try {
      const { id } = req.params;
      
      const course = await Course.findByPk(id);
      
      if (!course) {
        return next(
          new AppError('未找到该课程', StatusCodes.NOT_FOUND)
        );
      }

      // 检查权限：课程创建者或管理员
      if (course.teacherId !== req.user.id && req.user.role !== User.ROLES.ADMIN) {
        return next(
          new AppError('您没有权限修改此课程', StatusCodes.FORBIDDEN)
        );
      }

      // 不允许修改的字段
      const restrictedFields = ['teacherId', 'currentEnrollment'];
      restrictedFields.forEach(field => {
        if (req.body[field] !== undefined) {
          delete req.body[field];
        }
      });

      const updatedCourse = await course.update(req.body);
      this.success(res, updatedCourse, '课程更新成功');
    } catch (error) {
      this.error(res, '更新课程失败', StatusCodes.INTERNAL_SERVER_ERROR, error);
    }
  }

  /**
   * 删除课程（课程创建者或管理员）
   */
  async deleteCourse(req, res, next) {
    try {
      const { id } = req.params;
      
      const course = await Course.findByPk(id);
      
      if (!course) {
        return next(
          new AppError('未找到该课程', StatusCodes.NOT_FOUND)
        );
      }

      // 检查权限：课程创建者或管理员
      if (course.teacherId !== req.user.id && req.user.role !== User.ROLES.ADMIN) {
        return next(
          new AppError('您没有权限删除此课程', StatusCodes.FORBIDDEN)
        );
      }

      // 检查是否有学生选课
      const enrollmentCount = await Enrollment.count({
        where: { courseId: id, status: Enrollment.STATUS.SELECTED }
      });

      if (enrollmentCount > 0) {
        return next(
          new AppError('该课程已有学生选课，无法删除', StatusCodes.BAD_REQUEST)
        );
      }

      await course.destroy();
      this.success(res, null, '课程删除成功');
    } catch (error) {
      this.error(res, '删除课程失败', StatusCodes.INTERNAL_SERVER_ERROR, error);
    }
  }

  /**
   * 获取我教授的课程（教师）
   */
  async getMyTeachingCourses(req, res, next) {
    try {
      // 只有教师可以查看自己教授的课程
      if (req.user.role !== User.ROLES.TEACHER && req.user.role !== User.ROLES.ADMIN) {
        return next(
          new AppError('只有教师可以查看教授的课程', StatusCodes.FORBIDDEN)
        );
      }

      const { 
        page = 1, 
        limit = 10, 
        status,
        sortBy = 'createdAt',
        sortOrder = 'DESC'
      } = req.query;

      const where = { teacherId: req.user.id };
      if (status) where.status = status;

      // 排序
      const order = [];
      if (sortBy) {
        order.push([sortBy, sortOrder || 'DESC']);
      }

      // 查询课程及选课学生信息
      const result = await Course.findAndCountAll({
        where,
        include: [
          {
            model: Enrollment,
            as: 'enrollments',
            include: [
              {
                model: User,
                as: 'student',
                attributes: ['id', 'name', 'email']
              }
            ]
          }
        ],
        order,
        offset: (page - 1) * limit,
        limit: parseInt(limit, 10),
        distinct: true
      });

      // 计算每门课程的选课人数
      const courses = result.rows.map(course => {
        const courseJson = course.toJSON();
        courseJson.enrollmentCount = course.enrollments.length;
        return courseJson;
      });

      this.success(res, {
        total: result.count,
        page: parseInt(page, 10),
        limit: parseInt(limit, 10),
        data: courses,
      }, '获取成功');
    } catch (error) {
      this.error(res, '获取教授课程失败', StatusCodes.INTERNAL_SERVER_ERROR, error);
    }
  }

  /**
   * 获取课程的学生列表
   */
  async getCourseEnrollments(req, res, next) {
    try {
      const { courseId } = req.params;
      
      // 检查课程是否存在
      const course = await Course.findByPk(courseId);
      if (!course) {
        return next(
          new AppError('课程不存在', StatusCodes.NOT_FOUND)
        );
      }

      // 获取课程的选课学生
      const enrollments = await Enrollment.findAll({
        where: { courseId, status: Enrollment.STATUS.SELECTED },
        include: [
          {
            model: User,
            as: 'student',
            attributes: ['id', 'name', 'email', 'username']
          }
        ]
      });

      // 提取学生信息
      const students = enrollments.map(enrollment => enrollment.student);

      this.success(res, {
        courseId,
        courseName: course.name,
        studentCount: students.length,
        students
      }, '获取成功');
    } catch (error) {
      this.error(res, '获取课程学生列表失败', StatusCodes.INTERNAL_SERVER_ERROR, error);
    }
  }
}

export default new CourseController();
